import React, {useRef} from "react";
import {DeleteShippingPlanDetail, ModifyShippingPlan, ShippingPlanDetail, ShippingPlanVO} from "@/apiNew/shippingPlan";
import {ActionType, EditableProTable, ProColumns} from "@ant-design/pro-table";
import {DatePicker, notification, Popconfirm, Select, Tag} from "antd";
import {useCompanyList} from "@/views/productManagement/common/useCompanyList";
import {noop} from "@/views/productManagement/common/func";
import {ADD_ITEM_FLAG, isAddItem, isSuccessRes} from "@/types/common";
import moment from 'moment'
import {useShops} from "@/views/productManagement/common/useShops";
import {paramsDataFormat} from "@/types/format";
import {FormInstance} from "antd/lib/form";
import {sleep} from "@/types/jsUtil";

interface ShippingDetailsCompProps {
  shippingDetails: ShippingPlanVO
  actionRef: React.MutableRefObject<ActionType | undefined>
}

const DateSelect = ({value = '', onChange = noop}) => {
  // @ts-ignore
  return <DatePicker allowClear={false} value={moment(value)} onChange={(...args) => {
    onChange(...args)
  }} showTime/>
}

export const ShippingDetailsComp = ({shippingDetails, actionRef}: ShippingDetailsCompProps) => {
  const {expressCompanySelectProps, findById} = useCompanyList()
  const {selectProps, findById: findByShopId,} = useShops()

  // const CompanySelect = ({value = '', onChange = noop}) => {
  //   return <Select
  //     options={expressCompanySelectProps.options}
  //     value={value}
  //     onChange={onChange}>
  //   </Select>
  // }
  console.log(shippingDetails)
  const getShipVo = ()=>shippingDetails

  const columns: ProColumns<ShippingPlanDetail>[] = [
    {
      title: '规则名称', dataIndex: 'Name', width: 200,
      formItemProps: {
        rules: [{required: true, message: '此项为必填项',},],
      },

    },
    {
      title: '说明', dataIndex: 'Remark', width: 200,
      formItemProps: {
        rules: [{required: true, message: '此项为必填项',},],
      },
    },

    {
      title: '商户名', dataIndex: 'ShopId',
      render: (text, record, index) =>
        (<Tag color="geekblue">{findByShopId(record.ShopId)?.label ?? '-'}</Tag>)
      , renderFormItem: (_, {isEditable}) => {
        return <Select {...selectProps}/>
      },
      width: 200,
      // formItemProps: {
      //   rules: [{required: true, message: '此项为必填项',},],
      // },
    },

    {
      title: '开始时间', dataIndex: 'StartTime',
      renderFormItem: (_, {isEditable,}) => {
        return <DateSelect/>
      },
      formItemProps: {
        rules: [{required: true, message: '此项为必填项',},],
      },
    },

    {
      title: '结束时间', dataIndex: 'EndTime',
      renderFormItem: (_, {isEditable,}, form) => {
        // console.log('form.getFieldsValue() %o', form.getFieldsValue())
        // form.validateFields()
        return <DateSelect/>
      },

      formItemProps: (form) => {
        const rows = form.getFieldsValue()
        // const [curRowKey] = Object.keys(rows);
        // const {StartTime,EndTime} = rows[curRowKey];
        return {
          rules: [
            {required: true, message: '此项为必填项',},
          ],
        }
      }
    },

    {
      title: '被替代物流公司', dataIndex: 'SrcShippingCompanyId',
      render: (text, record, index) =>
        (<Tag color="geekblue">{findById(record.SrcShippingCompanyId)?.label ?? '-'}</Tag>)
      ,
      renderFormItem: (_, {isEditable,}) => {
        return <Select options={expressCompanySelectProps.options}/>
      },
      formItemProps: {
        rules: [{required: true, message: '此项为必填项',},],
      },
      width: 290,

    },
    {
      width: 290,

      title: '替代物流公司', dataIndex: 'ShippingCompanyId',
      render: (text, record, index) =>
        (<Tag color="geekblue">{findById(record.ShippingCompanyId)?.label ?? '-'}</Tag>)
      ,
      renderFormItem: (_, {isEditable,}) => {
        return <Select options={expressCompanySelectProps.options}/>
      },
      formItemProps: {
        rules: [{required: true, message: '此项为必填项',},],
      },
    },

    {
      title: '操作',
      valueType: 'option',
      width: 250,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action.startEditable?.(record.ShippingPlanDetailId);
          }}
        >
          编辑
        </a>,

        <Popconfirm
          key="delete"
          title="Are you sure to delete this task?"
          onConfirm={async () => {
            // setDataSource(dataSource.filter((item) => item.ShippingPlanId !== record.ShippingPlanId));
            try {
              const responseData = await DeleteShippingPlanDetail(record.ShippingPlanDetailId);
              if (isSuccessRes(responseData)) {
                notification.success({message: '删除数据成功',})
                actionRef.current?.reload();
              }
            } catch (e) {
              console.log(e)
            }
          }}
          okText="Yes"
          cancelText="No"
        >
          <a href="#">删除</a>
        </Popconfirm>,

        <EditableProTable.RecordCreator
          key="copy-row"
          record={{
            ...record,
            ShippingPlanDetailId: ADD_ITEM_FLAG,
          }}
        >
          <a>复制此行到末尾</a>
        </EditableProTable.RecordCreator>,
      ],
    },
  ];

  const {ShippingPlanId} = shippingDetails;

  const {ShippingPlanDetails, Name} = shippingDetails
  // const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);

  // formRef.current.

  return <EditableProTable<ShippingPlanDetail>
    rowKey="ShippingPlanDetailId"
    // headerTitle={<Tag color="purple">{`${Name}规则列表`}</Tag>}
    headerTitle={false}
    search={false}
    options={false}
    pagination={false}

    recordCreatorProps={
      {
        creatorButtonText: `新增 [${Name}] 规则`,
        position: 'bottom',
        record: {
          "ShippingPlanDetailId": ADD_ITEM_FLAG,
          // @ts-ignore
          ShippingPlanId,
          "SrcShippingCompanyId": '',
          "ShippingCompanyId": '',
          "ShopId": '',
          "Name": '',
          "StartTime": new Date(),
          "EndTime": new Date(),
          "Remark": '',
        },
      }
    }

    columns={columns}
    value={ShippingPlanDetails}
    editable={{
      // editableKeys,
      onSave: async (key, row, ...newLine) => {

        // await sleep(2000)
        console.log(key, row, newLine)
        const isEditStatus = !isAddItem(key)
        let ShippingPlanDetails = shippingDetails.ShippingPlanDetails
        console.log("new row ", row, isEditStatus)
        if (isEditStatus) {
          ShippingPlanDetails = ShippingPlanDetails.filter(v => v.ShippingPlanDetailId !== row.ShippingPlanDetailId)
        }

        try {
          const responseData = await ModifyShippingPlan({
            ...shippingDetails,
            ShippingPlanDetails: [
              ...ShippingPlanDetails,
              paramsDataFormat({
                ...row, ...(() => isEditStatus ? {} : {
                  "ShippingPlanDetailId": 0
                })()
              }, ['StartTime', 'EndTime'])
            ]
          } as any)
          if (isSuccessRes(responseData)) {
            notification.success({message: '修改数据成功',})
            actionRef.current?.reload();
            return true
          }
          return false
        } catch (e) {
          console.log(e)
          notification.warn({message: '修改数据失败',})
          return false
        }
      },
      // onChange: setEditableRowKeys,
    }}
  />
}
